<?php
declare(strict_types=1);

namespace SixShop\WechatPay;

use SixShop\Wechat\Service\MiniApp;
use think\Facade;
use WeChatPay\Builder;
use WeChatPay\BuilderChainable;

/**
 * @method static BuilderChainable getBuilderChainable()
 */
class WechatPayBuilder extends Facade
{
    public function __construct(
        private readonly Config   $config,
        private ?BuilderChainable $builderChainable = null,
        private ?MiniApp          $miniApp = null
    )
    {
    }

    protected static function getFacadeAccessor(): string
    {
        return self::class;
    }

    public function getBuilderChainable(): BuilderChainable
    {

        if ($this->builderChainable === null) {
            $config = [
                'mchid' => $this->config->mchid,
                'serial' => $this->config->serial_no,
                'privateKey' => $this->config->apiclient_key,
                'certs' => [
                    $this->config->public_key_id => $this->config->public_key,
                ],
            ];
            if ($this->config->platform_no) {
                $config['certs'][$this->config->platform_no] = $this->config->platform_cert;
            }
            $this->builderChainable = Builder::factory($config);
        }
        return $this->builderChainable;
    }

    public function getConfig(): Config
    {
        return $this->config;
    }

    public function getMiniApp(): MiniApp
    {
        if ($this->miniApp === null) {
            $this->miniApp = app()->make(MiniApp::class, [
                $this->config->app_id,
            ]);
        }
        return $this->miniApp;
    }
}